<?php

namespace app\mini\controller;

use app\admin\model\Goods;
use app\company\model\CompanyGoodsRule;
use app\company\model\CompanyOrderDetail;
use app\company\model\StoreSupplier;

class StoreGoods extends Base
{
    public function list()
    {
        $param = $this->request->param();
        $companyId = $this->userInfo->company_id;
        $isSalesman = $this->userInfo->is_salesman; // 是否是业务员
        $supplierId = $this->userInfo->supplier_id; // 用户所绑定的经销商
        if($isSalesman != 1 ) return $this->error('您不是业务员，无法查看商品');
        // 判断门店是否包含业务员所属经销商
        $supplier_ids = StoreSupplier::gs($companyId)->where('store_id', $param['store_id'])->column('supplier_id');
        if (!in_array($supplierId, $supplier_ids)) return $this->error('该门店暂无此经销商的商品！');
        //查询门店所有商品
        $sql = (new CompanyOrderDetail())->alias('order')
                                         ->join('goods', 'goods.id = order.goods_id')
                                         ->join(['dt_company_goods' => 'company'], 'company.goods_id = order.goods_id')
                                         ->where('order.company_id', $companyId)
                                         ->where('company.status', 1)//控制商品上下架
                                         ->where('company.company_id', $companyId)//控制商品上下架
                                         ->where('order.supplier_id', $supplierId);

        if ($name = request()->param('name', '')) {
            $sql = $sql->where('goods.name', 'like', '%' . $name . '%');
        }

        if ($goods_cate_id = request()->param('goods_cate_id', 0)) {
            $sql = $sql->where('goods.goods_cate_id', $goods_cate_id);
        }
        $sql   = $sql->field('order.goods_id')->group("order.goods_id");
        $count = $sql->count();
        $list  = $sql->page($param['page'], $param['limit'])->order('order.goods_id')->select();
        foreach ($list as $key => $item) {
            $item->goods = Goods::where('id', $item->goods_id)->field('name,img,spec_type')->withTrashed()->find();
            $goods       = (new CompanyGoodsRule())->gs($companyId)
                                                   ->withTrashed()
                                                   ->where('goods_id', $item->goods_id)
                                                   ->order('money')
                                                   ->field('money,goods_rule_id')->find();//获取价格
            if (!$goods) {
                unset($list[$key]);
                continue;
            }
            $item->goods_rule_id = $goods->goods_rule_id;
            $item->price         = $goods->money;
            //销量 所有商品
            $item->sales = (int)redis()->zScore(xsGoodsKey() . $this->company_id, $item->goods_id);
        }
        return $this->success('获取成功',compact('count','list'));
    }
}